/**
 * 
 */
package com.sian.gencode.utils;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.URL;

import com.sian.gencode.tablestructure.TableUtils;

import com.jida.utils.GenFile;

/**
 * 生成pojoMain
 * @author desert 
 * @version 1.0 2014/02/17
 */
public class GenPojoMain {
	
	/**
	 * 获取工程的根路径
	 * @return projectpath
	 */
	public String getProjectRoot(){
		
		 URL url = GenPojoMain.class.getResource("");
		
		 String path = url.toString().replace("file:/", "");
		 
		 path = path.replace("com/sian/gencode/utils/", "");
		 
		 path = path.replace("WebRoot/WEB-INF/classes/","src");
		 
		 System.out.println("类文件生成路径为："+path);
		
		return path;
	}
	
	/**
	 * 生成pojo的核心方法
	 * @param packageName  包的名称
	 * @param ModelName    模块的名称
	 * @param tableName    表的名称
	 * @param databaseName  数据库的名称
	 */
	public void genPojoMain(String packageName,String ModelName ,String tableName,String databaseName,String fileName){
		
		//生成pojo类
		StringBuffer sb = new StringBuffer();
		
		//包名
		sb.append("package "+packageName+".pojo;");
		
		//导入的类名
		sb.append("import java.io.Serializable; \r\n");
		sb.append("import com.jida.annotation.GenField; \r\n");
		sb.append("import com.jida.annotation.GenModel; \r\n");
		sb.append("import com.jida.annotation.GenTable; \r\n");
		sb.append("import java.util.*; \r\n");
		
		//加入三个空白行
		sb.append(" \r\n ");
		sb.append(" \r\n ");
		sb.append(" \r\n ");
		
		//文件的类定义
		sb.append("@GenTable(name=\""+tableName+"\") \r\n");
		sb.append("@GenModel(packageName=\""+packageName+"\",modelName=\""+ModelName+"\")  \r\n");
		sb.append(" public class "+fileName+"Pojo implements Serializable{  \r\n");
		
		TableUtils tu = new TableUtils();
		
		
		sb.append(tu.construtsPojo(tableName, databaseName));
		
		
		sb.append("}");
		
		//生成文件
		String FilePath  = this.getProjectRoot();
        
		 GenFile  genFile = new GenFile();
		 try {
			File file = genFile.createFile(FilePath+File.separator+packageName.replace(".", "/")+"/pojo", fileName+"Pojo.java");
		    genFile.writeFile(file, sb.toString()); //向文件中写内容
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] arg){
		GenPojoMain  genPojoMain = new GenPojoMain();
		
		/**
		@ param packageName  包的名称
		  @param ModelName    模块的名称
		  @param tableName    表的名称
		  @param databaseName  数据库的名称名
		  @param fileName pojoFileName  pojo类的称*/
		
		genPojoMain.genPojoMain("com.sian.audit", "audit", "audit", "scbm", "audit");
		//genPojoMain.genPojoMain("net.lwyj.safeitemsetting", "safetyrelation", "t_safety_relation", "psms", "InformationiSsuance");
		
	} 

}
